package com.yuanqi.contoller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuanqi.entity.WareTransfer;
import com.yuanqi.entity.WareTransferItem;
import com.yuanqi.service.WareTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 库存调拨控制器
 */
@RestController
@RequestMapping("/ware/transfer")
@CrossOrigin(origins = "*")
public class WareTransferController {
    
    @Autowired
    private WareTransferService wareTransferService;
    
    /**
     * 分页查询调拨单列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> listTransfers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String transferCode,
            @RequestParam(required = false) Long fromWarehouseId,
            @RequestParam(required = false) Long toWarehouseId,
            @RequestParam(required = false) String transferType,
            @RequestParam(required = false) Integer status) {
        
        try {
            IPage<WareTransfer> result = wareTransferService.listTransfers(
                page, size, transferCode, fromWarehouseId, toWarehouseId, transferType, status);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("message", "查询成功");
            response.put("data", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 获取调拨单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getTransferDetail(@PathVariable Long id) {
        try {
            Map<String, Object> result = wareTransferService.getTransferDetail(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("message", "查询成功");
            response.put("data", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 创建调拨单
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createTransfer(@RequestBody Map<String, Object> request) {
        try {
            // 参数验证
            if (request.get("fromWarehouseId") == null || request.get("toWarehouseId") == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("message", "调出仓库和调入仓库不能为空");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 解析调拨单基本信息
            WareTransfer transfer = new WareTransfer();
            transfer.setTransferCode((String) request.get("transferCode"));
            transfer.setFromWarehouseId(Long.valueOf(request.get("fromWarehouseId").toString()));
            transfer.setToWarehouseId(Long.valueOf(request.get("toWarehouseId").toString()));
            transfer.setTransferType((String) request.get("transferType"));
            transfer.setCreatedBy((String) request.get("createdBy"));
            transfer.setRemark((String) request.get("remark"));
            
            // 处理调拨日期
            if (request.get("transferDate") != null) {
                try {
                    String dateStr = request.get("transferDate").toString();
                    if (!dateStr.isEmpty()) {
                        transfer.setTransferDate(java.sql.Date.valueOf(dateStr));
                    }
                } catch (Exception e) {
                    // 如果日期格式不正确，使用当前日期
                    transfer.setTransferDate(new java.sql.Date(System.currentTimeMillis()));
                }
            } else {
                transfer.setTransferDate(new java.sql.Date(System.currentTimeMillis()));
            }
            
            // 解析调拨明细
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> itemsData = (List<Map<String, Object>>) request.get("items");
            List<WareTransferItem> items = null;
            
            if (itemsData != null && !itemsData.isEmpty()) {
                items = itemsData.stream().map(itemData -> {
                    WareTransferItem item = new WareTransferItem();
                    
                    // 验证必要字段
                    if (itemData.get("skuId") == null) {
                        throw new IllegalArgumentException("SKU ID不能为空");
                    }
                    if (itemData.get("qty") == null) {
                        throw new IllegalArgumentException("调拨数量不能为空");
                    }
                    
                    item.setSkuId(Long.valueOf(itemData.get("skuId").toString()));
                    item.setQty(new java.math.BigDecimal(itemData.get("qty").toString()));
                    
                    // 处理单价，如果为空则默认为0
                    if (itemData.get("unitPrice") != null && !itemData.get("unitPrice").toString().isEmpty()) {
                        item.setUnitPrice(new java.math.BigDecimal(itemData.get("unitPrice").toString()));
                    } else {
                        item.setUnitPrice(java.math.BigDecimal.ZERO);
                    }
                    
                    item.setBatchNo((String) itemData.get("batchNo"));
                    item.setRemark((String) itemData.get("remark"));
                    
                    // 处理有效期
                    if (itemData.get("expiryDate") != null && !itemData.get("expiryDate").toString().isEmpty()) {
                        try {
                            String dateStr = itemData.get("expiryDate").toString();
                            item.setExpiryDate(java.sql.Date.valueOf(dateStr));
                        } catch (Exception e) {
                            // 如果日期格式不正确，设置为null
                            item.setExpiryDate(null);
                        }
                    }
                    
                    return item;
                }).toList();
            }
            
            boolean success = wareTransferService.createTransfer(transfer, items);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "创建成功");
                response.put("data", transfer);
            } else {
                response.put("code", 500);
                response.put("message", "创建失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "创建失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 更新调拨单
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateTransfer(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        try {
            // 解析调拨单基本信息
            WareTransfer transfer = new WareTransfer();
            transfer.setId(id);
            transfer.setTransferCode((String) request.get("transferCode"));
            transfer.setFromWarehouseId(Long.valueOf(request.get("fromWarehouseId").toString()));
            transfer.setToWarehouseId(Long.valueOf(request.get("toWarehouseId").toString()));
            transfer.setTransferType((String) request.get("transferType"));
            transfer.setCreatedBy((String) request.get("createdBy"));
            transfer.setRemark((String) request.get("remark"));
            
            // 解析调拨明细
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> itemsData = (List<Map<String, Object>>) request.get("items");
            List<WareTransferItem> items = null;
            
            if (itemsData != null && !itemsData.isEmpty()) {
                items = itemsData.stream().map(itemData -> {
                    WareTransferItem item = new WareTransferItem();
                    item.setSkuId(Long.valueOf(itemData.get("skuId").toString()));
                    item.setQty(new java.math.BigDecimal(itemData.get("qty").toString()));
                    item.setUnitPrice(new java.math.BigDecimal(itemData.get("unitPrice").toString()));
                    item.setBatchNo((String) itemData.get("batchNo"));
                    item.setRemark((String) itemData.get("remark"));
                    
                    // 处理有效期
                    if (itemData.get("expiryDate") != null) {
                        item.setExpiryDate(new java.util.Date(itemData.get("expiryDate").toString()));
                    }
                    
                    return item;
                }).toList();
            }
            
            boolean success = wareTransferService.updateTransfer(transfer, items);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "更新成功");
                response.put("data", transfer);
            } else {
                response.put("code", 500);
                response.put("message", "更新失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "更新失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 提交审核
     */
    @PostMapping("/{id}/submit")
    public ResponseEntity<Map<String, Object>> submitForAudit(@PathVariable Long id) {
        try {
            boolean success = wareTransferService.submitForAudit(id);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "提交审核成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "提交审核失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "提交审核失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 审核通过
     */
    @PostMapping("/{id}/approve")
    public ResponseEntity<Map<String, Object>> approveTransfer(@PathVariable Long id, @RequestParam(required = false) String approvedBy) {
        try {
            boolean success = wareTransferService.approveTransfer(id, approvedBy);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "审核通过成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "审核通过失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "审核通过失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 审核驳回
     */
    @PostMapping("/{id}/reject")
    public ResponseEntity<Map<String, Object>> rejectTransfer(@PathVariable Long id, @RequestParam(required = false) String approvedBy) {
        try {
            boolean success = wareTransferService.rejectTransfer(id, approvedBy);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "审核驳回成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "审核驳回失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "审核驳回失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 完成调拨
     */
    @PostMapping("/{id}/complete")
    public ResponseEntity<Map<String, Object>> completeTransfer(@PathVariable Long id, @RequestParam(required = false) String completedBy) {
        try {
            boolean success = wareTransferService.completeTransfer(id, completedBy);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "调拨完成成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "调拨完成失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "调拨完成失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 删除调拨单
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteTransfer(@PathVariable Long id) {
        try {
            boolean success = wareTransferService.deleteTransfer(id);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 0);
                response.put("message", "删除成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "删除失败");
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "删除失败: " + e.getMessage());
            response.put("data", null);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}

